package com.gen.info.generate_cluster_information.service;

import com.gen.info.generate_cluster_information.config.ParamModle;
import com.gen.info.generate_cluster_information.config.SourceDataSource;
import com.gen.info.generate_cluster_information.config.TargetDataSource;
import com.gen.info.generate_cluster_information.mode.ConnectionInfo;
import com.gen.info.generate_cluster_information.mode.OceanBaseClusterInfoDO;
import com.gen.info.generate_cluster_information.mode.RSPoolVO;
import com.gen.info.generate_cluster_information.mode.TenantVO;
import com.gen.info.generate_cluster_information.util.DBUtil;
import com.gen.info.generate_cluster_information.util.OceanBaseSqlObjectGenerateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
@Service
@Slf4j
public class CreateTenant {
    @Autowired
    private SourceDataSource sourceDataSource;
    @Autowired
    private TargetDataSource targetDataSource;
    @Autowired
    private ParamModle paramModle;
    public  void CreateTenantRS(ArrayList<TenantVO> tenantVOS){
        //构建连接信息
        ConnectionInfo connectionInfo = new ConnectionInfo();
        BeanUtils.copyProperties(sourceDataSource,connectionInfo);
        log.info("连接信息构建完成："+connectionInfo.toString());
        for (TenantVO tenantVO : tenantVOS) {
            try {
                final Connection connetcion = DBUtil.getConnetcion(connectionInfo);
                final PreparedStatement smt = DBUtil.getPreparedStatement(connetcion,
                        "select tenant_name from oceanbase.__all_tenant where tenant_name = ?");
                smt.setString(1,tenantVO.getTenantName());
                final ResultSet rs = smt.executeQuery();
                // DBUtil.closeConnection();
                //判断租户是否已经存在
                if (!rs.next()) {
                    log.info("开始创建租户"+tenantVO.getTenantName());
                    final Statement stmt = DBUtil.getCreateStatement(connetcion);
                    final String tenantSql = OceanBaseSqlObjectGenerateUtil.getTenantSql(tenantVO);
                    stmt.executeUpdate(tenantSql);
                    log.info("租户"+tenantVO.getTenantName()+"创建完成");
                   // DBUtil.closeConnection();
                     while (!smt.executeQuery().next()){
                         log.info("业务租户正在准备中");
                     }
                    //判断是oboracle还是obmysql
                    log.info("创建业务租户的连接");
                        ConnectionInfo connectionInfo2 = new ConnectionInfo();
                        BeanUtils.copyProperties(targetDataSource,connectionInfo2);
                        connectionInfo2.setPassword("");
                        connectionInfo2.setTenant_name(tenantVO.getTenantName());
                        final Connection conn = DBUtil.getConnetcion(connectionInfo2);
                    if (tenantVO.getDbtype().equalsIgnoreCase("oracle")){
                        log.info("oracle暂时未开发");
                    }else {
                        //初始化租户密码
                        log.info("初始化租户"+connectionInfo2.getTenant_name()+"的密码为："+targetDataSource.getPassword());
                        final PreparedStatement preparedStatement = conn.
                                prepareStatement("alter user 'root'@'%' identified by '"
                                        + targetDataSource.getPassword()+"'");
                        preparedStatement.addBatch();
                        //初始化只读用户
                        log.info("初始化只读用户开始");
                        preparedStatement.addBatch(OceanBaseSqlObjectGenerateUtil.getReadOnlyUserSql());
                        preparedStatement.addBatch("GRANT SELECT  ON *.* TO readonly");
                        //初始化参数模版
                        log.info("初始化参数模版！！");
                        paramModle.getParam().forEach((k,v)->{
                            try {
                                preparedStatement.addBatch("set global "+k+"="+v);
                            } catch (SQLException throwables) {
                                throwables.printStackTrace();
                            }
                        });
                        preparedStatement.executeBatch();
                        preparedStatement.clearBatch();
                        //DBUtil.closeConnection();
                        log.info("初始化参数模版完成");
                        log.info("租户的初始化密码为："+targetDataSource.getPassword());
                    }
                    log.info("租户" + tenantVO.getTenantName() + "建立成功！！");
                }else {
                    log.info("租户"+tenantVO.getTenantName()+"已经被创建！！");
                }
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }finally {
               // DBUtil.closeConnection();
            }
            //System.out.println("租户信息："+tenantVO.toString());
        }
    }
    public  ArrayList<TenantVO> getTenantRS(Collection<OceanBaseClusterInfoDO> oceanBaseClusterInfoDOS,HashMap<String, RSPoolVO> rSUnitVOHashMap){
        //    final ArrayList<RSUnitVO> rsUnitVOS = new ArrayList<>();
        final ArrayList<TenantVO> tenantVOS = new ArrayList<>();
        int counter = 1;
        for (OceanBaseClusterInfoDO oceanBaseClusterInfoDO : oceanBaseClusterInfoDOS) {
            final TenantVO tenantVO = new TenantVO();
            tenantVO.setTenantName(oceanBaseClusterInfoDO.getTenant());
            tenantVO.setPrimaryZone(oceanBaseClusterInfoDO.getPrimary_zone());
            tenantVO.setResourcePools(rSUnitVOHashMap.get(oceanBaseClusterInfoDO.getTenant()).getPoolName());
            tenantVO.setMode(oceanBaseClusterInfoDO.getMode());
            tenantVO.setDbtype(oceanBaseClusterInfoDO.getDbtype());
            tenantVOS.add(tenantVO);
            counter++;
        }
        return tenantVOS;
    }
}
